//
//  FriendSelViewController.m
//  FootPrint
//
//  Created by alex tao on 4/9/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "FriendSelViewController.h"
#import "FriendSelCell.h"

@interface FriendSelViewController ()

@end

@implementation FriendSelViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _parser = [[FriendParser alloc] init];
        _parser.delegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self updateVisiableView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setFriendTable:nil];
    [self setSegmentControl:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [_parser release];
    self.selGroup = nil;
    self.excludeFriends = nil;
    self.selDelegate = nil;
    self.selFriends = nil;
    self.allFriends = nil;
    [_friendTable release];
    [_segmentControl release];
    [super dealloc];
}

- (void) updateVisiableView
{
    if (_segmentControl.selectedSegmentIndex == 0) {
        if ([FriendManager sharedInstance].isLatestList) {
            [self listUpdated:[[FriendManager sharedInstance] allFriends]];
        } else {
            [_parser updateFriendListForUid:[GConfig getUserId]];
        }
    } else {
        if ([FriendManager sharedInstance].isLatestGroup) {
            [self groupUpdated:[[FriendManager sharedInstance] allGroup]];
        } else {
            [_parser updateGroupListForUid:[GConfig getUserId]];
        }
    }
}

- (void)listUpdated:(NSArray*)alls
{
    NSMutableArray * tmpList = [[[NSMutableArray alloc] initWithCapacity:8] autorelease];
    for (FriendQueryResponseMessage_FriendList * msg in alls) {
        BOOL exclude = NO;
        for (NSNumber * oneId in _excludeFriends) {
            if (msg.user.id == [oneId longLongValue]) {
                exclude = YES;
                break;
            }
        }
        if (!exclude) {
            [tmpList addObject:msg];
        }
    }
    
    self.allFriends = tmpList;
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        [_friendTable reloadData];
    }
}

- (void)groupUpdated:(NSArray*)alls
{
    self.allGroup = alls;
    
    if (_segmentControl.selectedSegmentIndex == 1) {
        [_friendTable reloadData];
    }
}

- (void)setSelFriends:(NSMutableArray *)selFriends
{
    [_selFriends release];
    _selFriends = [selFriends mutableCopy];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_segmentControl.selectedSegmentIndex == 1) {
        return self.allGroup.count;
    }
    return self.allFriends.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *friendSelCellIdentifier = @"friendSelCellIdentifier";
    FriendSelCell *cell = [tableView dequeueReusableCellWithIdentifier:friendSelCellIdentifier];
    if (cell == nil) {
        cell = [[[FriendSelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendSelCellIdentifier] autorelease];
    }
    
    if (_segmentControl.selectedSegmentIndex == 1)
    {
        GroupMessage * msg = [_allGroup objectAtIndex:indexPath.row];
        [cell updateCellGroupInfo:msg];
        
        BOOL isSelected = NO;
        for (GroupMessage * status in _selGroup) {
            if (status.id == msg.id) {
                isSelected = YES;
                break;
            }
        }
        cell.redioImage.highlighted = isSelected;
    }
    else
    {
        FriendQueryResponseMessage_FriendList * msg = [_allFriends objectAtIndex:indexPath.row];
        [cell updateCellInfo:msg];
        
        BOOL isSelected = NO;
        for (NSNumber * status in _selFriends) {
            if ([status longLongValue] == msg.user.id) {
                isSelected = YES;
                break;
            }
        }
        cell.redioImage.highlighted = isSelected;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_segmentControl.selectedSegmentIndex == 1)
    {
        GroupMessage * msg = [_allGroup objectAtIndex:indexPath.row];
        BOOL isSelected = NO;
        NSInteger selIdx = -1;
        for (GroupMessage * status in _selGroup) {
            selIdx++;
            if (status.id == msg.id) {
                isSelected = YES;
                break;
            }
        }
        
        if (isSelected && selIdx >= 0) {
            [_selGroup removeObjectAtIndex:selIdx];
        } else {
            if (nil == _selGroup) {
                _selGroup = [[NSMutableArray alloc] initWithCapacity:1];
            }
            [_selGroup addObject:msg];
        }
    }
    else
    {
        FriendQueryResponseMessage_FriendList * msg = [_allFriends objectAtIndex:indexPath.row];
        BOOL isSelected = NO;
        NSInteger selIdx = -1;
        for (NSNumber * status in _selFriends) {
            selIdx++;
            if ([status longLongValue] == msg.user.id) {
                isSelected = YES;
                break;
            }
        }
        
        if (isSelected && selIdx >= 0) {
            [_selFriends removeObjectAtIndex:selIdx];
        } else {
            if (nil == _selFriends) {
                _selFriends = [[NSMutableArray alloc] initWithCapacity:1];
            }
            [_selFriends addObject:[NSNumber numberWithLongLong:msg.user.id]];
        }
    }
    
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [tableView endUpdates];
    
    NSLog(@"sel cnt = %d", _selFriends.count);
}


- (IBAction)exit:(id)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)okSelect:(id)sender
{
    NSMutableArray * selStatus = [NSMutableArray arrayWithCapacity:_selFriends.count];
    for (NSNumber * oneId in _selFriends) {
        for (FriendQueryResponseMessage_FriendList * oneFriend in _allFriends) {
            if ([oneId longLongValue] == oneFriend.user.id) {
                EventMessage_UserStatus * status = [[[[EventMessage_UserStatus builder] setStatus:eStatWait] setUser:oneFriend.user] build];
                if (status) {
                    [selStatus addObject:status];
                }
            }
        }
    }
    
    BOOL okSelect = YES;
    if ([_selDelegate respondsToSelector:@selector(willUpdateFriendSel:groupSel:)]) {
        okSelect = [_selDelegate willUpdateFriendSel:selStatus groupSel:_selGroup];
    }
    
    if (okSelect) {
        if ([_selDelegate respondsToSelector:@selector(didUpdateFriendSel:groupSel:)]) {
            [_selDelegate didUpdateFriendSel:selStatus groupSel:_selGroup];
        }
        [self exit:nil];
    }
}

- (IBAction)changeSegment:(id)sender
{
    [self updateVisiableView];
}


#pragma mark - delegate

- (void) didRecieveFriendList:(FriendQueryResponseMessage*)friends
{
    if (friends && friends.resultCode == 0) {
        [self listUpdated:[GToolUtil PBArr2NSArr:friends.friendList]];
    }
}

- (void) didRecieveGroupList:(GroupQueryResponseMessage*)group
{
    if (group && group.resultCode == 0) {
        [self groupUpdated:[GToolUtil PBArr2NSArr:group.list]];
    }
}

- (void) didDeleteGroup:(GroupDeleteResponseMessage*)result
{

}

@end
